/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.serialization;

import java.io.*;

import javax.faces.context.*;

import org.apache.commons.lang.*;
import org.metalframework.spring.test.*;
import org.metalframework.util.*;
import org.slf4j.*;
import org.springframework.context.*;
import org.springframework.web.jsf.*;

public class ReadableExternalizableProxy implements ExternalizableProxy, Serializable {
	
	private static final Logger logger = LoggerFactory.getLogger(ReadableExternalizableProxy.class);

	private Object target;
	
	public ReadableExternalizableProxy(Object target) {
		this.target = target;
	}
	
	public Object writeReplace() throws ObjectStreamException {
		return this;
	}
	
	public Object readResolve() throws ObjectStreamException {
		logger.trace("Resolving object to proxy for deserialization");
		
		if (target != null) {
			ApplicationContext applicationContext = getApplicationContext();
			if (applicationContext == null) {
				return target;
			}
			
			return ApplicationContextUtils.configure(target, applicationContext);
		}
		
		return target;
	}
	
	/**
	 * Lookups a Spring context to configure the target object being deserialized.
	 * 
	 * @return BeanFactory found or null if could not find a Spring context.
	 */
	protected ApplicationContext getApplicationContext() {
		if (isFacesEnvironment()) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			if (facesContext != null) {
				logger.trace("Deserialization is ocurring inside JavaServer Faces environment");
				return FacesContextUtils.getRequiredWebApplicationContext(facesContext);
			}
		}
		
		if (isTestEnvironment()) {
			ApplicationContext ctx = TestApplicationContextAccessor.getApplicationContext();
			if (ctx != null) {
				logger.trace("Deserialization is ocurring inside Test environment");
				return ctx;
			}
		}

		return null;
	}
	
	protected boolean isFacesEnvironment() {
		return isClassPresent("javax.faces.context.FacesContext");
	}
	
	protected boolean isTestEnvironment() {
		return isClassPresent("org.metalframework.spring.test.TestApplicationContextAccessor");
	}
	
	protected boolean isClassPresent(String name) {
		try {
			ClassUtils.getClass(name);
			return true;
		} catch (ClassNotFoundException e) {
			return false;
		}
	}
}
